package com.zhhtech.zhh.common

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.zhhtech.zhh.bean.UserInfoBean
import com.zhhtech.zhh.ui.activity.commom.LoginActivity
import com.zhhtech.zhh.ui.ext.toastMessageLong
import com.zhhtech.zhh.ui.helper.IMsa
import com.zhhtech.zhh.ui.helper.PropertyPlaceholderHelper
import com.zhhtech.zhh.ui.helper.mohsi.MoshiUtils
import com.zhhtech.zhh.ui.utils.SPUtils


fun IMsa.checkLogin(loginBlock: () -> Unit) {
    if (UserCache.isLogin) {
        loginBlock.invoke()
    } else {
        "请先登录".toastMessageLong()
        launchStartActivityForResult(LoginActivity::class.java) { loginBlock.invoke() }
    }
}

object UserCache {
    private const val SP_KEY_TOKEN: String = "SP_KEY_TOKEN"
    private const val SP_KEY_USER_INFO: String = "SP_KEY_USER_INFO"
    private const val SP_KEY_LQ_USER_INFO: String = "SP_KEY_LQ_USER_INFO"
    private const val SP_KEY_APP_CONFIG: String = "SP_KEY_APP_CONFIG"
    val isLogin: Boolean get() = getToken().isNotEmpty()

    // 用户token
    private var mToken: String? = null

    // 用户基本信息
    private var mUserInfoBean: UserInfoBean? = null

    // 用户基本信息
    private var jsonObject: JSONObject? = null

    fun getToken(): String {
        if (mToken == null) {
            mToken = SPUtils.getString(SP_KEY_TOKEN, "")
        }
        return mToken!!
    }

    fun getUserInfoBean(): UserInfoBean {
        if (mUserInfoBean == null) {
            mUserInfoBean = MoshiUtils.parseObject(SPUtils.getString(SP_KEY_USER_INFO, "{}"), UserInfoBean::class.java)
            saveUserInfoBean(mUserInfoBean)
        }
        return mUserInfoBean!!
    }

    fun getUserJson(): JSONObject? {
        getUserInfoBean()
        return jsonObject
    }

    fun changeUserInfoBean() {
        saveUserInfoBean(mUserInfoBean)
    }

    fun saveToken(token: String) {
        if (token.isNotEmpty()) {
            mToken = token
            SPUtils.put(SP_KEY_TOKEN, token)
        }
    }

    fun saveUserInfoBean(userInfoBean: UserInfoBean?) {
        if (userInfoBean == null) {
            return
        }
        mUserInfoBean = userInfoBean
        val userJson = JSON.toJSON(userInfoBean) as JSONObject
        PropertyPlaceholderHelper.parseObjToMap(null, userJson, userJson)
        jsonObject = userJson
        SPUtils.put(SP_KEY_USER_INFO, MoshiUtils.toJSONString(userInfoBean))
    }

    fun saveTenant(tenantId: Int) {
        SPUtils.put("key_tenant_id", tenantId)
    }

    fun logout() {
        mUserInfoBean = null
        jsonObject = null
        mToken = null
        SPUtils.remove(SP_KEY_TOKEN)
        SPUtils.remove(SP_KEY_USER_INFO)
    }
}